In [7]:
import numpy as np
from sklearn import preprocessing

In [8]:
# Example labels
labels = np.array([1,5,3,2,1,4,2,1,3])
print(labels)


[1 5 3 2 1 4 2 1 3]

In [9]:
# Create the encoder
lb = preprocessing.LabelBinarizer()

In [10]:
# Here the encoder finds the classes and assigns one-hot vectors 
lb.fit(labels)


Out[10]:
LabelBinarizer(neg_label=0, pos_label=1, sparse_output=False)

In [11]:
# And finally, transform the labels into one-hot encoded vectors
lb.transform(labels)


Out[11]:
array([[1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1],
       [0, 0, 1, 0, 0],
       [0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 0, 1, 0, 0]])
Expected Output array([[1, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 1, 0, 0]])